package com.minigame.datastore;

import jakarta.persistence.EntityManagerFactory;
import org.springframework.data.jpa.repository.JpaRepository;

import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DataStoreService {

    private final static DataStoreService instance = new DataStoreService();

    public  static DataStoreService getInstance(){
        return instance;
    }


    private int threadCount = 4;
    private DataStore[] dataStores;

    public void init(EntityManagerFactory entityManagerFactory){
        dataStores = new DataStore[threadCount];
        for(int i=0;i<threadCount;i++){
            dataStores[i] = new DataStore(entityManagerFactory.createEntityManager());
        }
    }


    public void stop(){
        for(DataStore e : dataStores){
            e.setStop(true);
        }
    }

    public <ID extends Serializable,T> void cacheInsert(JpaRepository<T,ID> jpaRepository,ID id, T t){
        dataStores[id.hashCode()%threadCount].insert(jpaRepository,id,t);
    }

    public <ID extends Serializable,T,BusID extends Serializable> void cacheInsert(JpaRepository<T,ID> jpaRepository,BusID busID,ID id, T t){
        dataStores[busID.hashCode()%threadCount].insert(jpaRepository,id,t);
    }

    public <ID extends Serializable,T> void cacheUpdate(JpaRepository<T,ID> jpaRepository,ID id, T t){
        dataStores[id.hashCode()%threadCount].update(jpaRepository,id,t);
    }

    public <ID extends Serializable,T,BusID extends Serializable> void cacheUpdate(JpaRepository<T,ID> jpaRepository,BusID busID,ID id, T t){
        dataStores[busID.hashCode()%threadCount].update(jpaRepository,id,t);
    }

    public <ID extends Serializable,T> void cacheDelete(JpaRepository<T,ID> jpaRepository,ID id, T t){
        dataStores[id.hashCode()%threadCount].delete(jpaRepository,id,t);
    }

    public <ID extends Serializable,T,BusID extends Serializable> void cacheDelete(JpaRepository<T,ID> jpaRepository,BusID busID,ID id, T t){
        dataStores[busID.hashCode()%threadCount].delete(jpaRepository,id,t);
    }
}
